package com.cg.bank.util;

import com.cg.bank.domain.User;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserBeanListHandler implements ResultSetHander<List<User>> {
    @Override
    public List<User> handle(ResultSet resultSet) throws SQLException {
        int resultCount = resultSet.getMetaData().getColumnCount();
        // 记录为空则返回
        if (resultCount == 0) {
            return null;
        }
        // 用于保存字段名的list
        List<String> columnCountList = new ArrayList<>();
        // 遍历字段名到list
        for (int i = 1; i <= resultCount; i++) {
            columnCountList.add(resultSet.getMetaData().getColumnLabel(i));
        }

        return processORM(resultSet, columnCountList);
    }

    private List<User> processORM(ResultSet resultSet, List<String> columnCountList) throws SQLException {
        // 封装所有用户信息list
        List<User> userList = new ArrayList<>();
        // 封装每个用户基本信息
        User user;
        while (resultSet.next()) {
            user = new User();
            user.setId(resultSet.getInt(columnCountList.get(0)));
            user.setAccount(resultSet.getString(columnCountList.get(1)));
            user.setUserName(resultSet.getString(columnCountList.get(2)));
            user.setBalance(resultSet.getDouble(columnCountList.get(3)));
            user.setAge(resultSet.getInt(columnCountList.get(4)));
            user.setSex(resultSet.getString(columnCountList.get(5)));
            user.setCreateTime(resultSet.getDate(columnCountList.get(6)));
            userList.add(user);
        }

        return userList;
    }
}
